<?php
header("Content-type: text/html; charset=utf-8");
//从指定目录获取所有文件
function read_files_by_dir($dir_path) {
    $files = array();
    if (is_dir($dir_path)) {
        if ($handle = opendir($dir_path)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != '.' && $file != '..' && $file != '.svn') {
                    $files[] = $file;
                }
            }
            closedir($handle);
        }
    }
    return $files;
}

//读取文件内容，并解析组合为规定的格式。
function read_file_data($file_path) {
    $content = file_get_contents($file_path);
    $content = preg_replace('/[\s]{2,}/si',' ',$content);
    $content = str_replace("'","\'",$content); 
    return  $content; 
}

//格式化文件名 xx.xx.html to page_xx_xx
function format_file_name($file_name) {
    $arr = explode('.',$file_name);
    return 'page_' . $arr[0] . '_' . $arr[1];
}


function html2js ($write_to,$file_name) {
    $files = read_files_by_dir($write_to);
    $content = '';

    for ($i=0; $i<count($files); $i++) {
        $temp = read_file_data($write_to . '/' . $files[$i]);
        $content .= 'window.view_page_cache["' . format_file_name($files[$i]) . '"] = \'' . $temp . '\';';
    }
    file_put_contents($write_to . '/' . $file_name, $content);
}


if (isset($_POST['path'])) {
    $relative_path = $_POST['path'];
    $relative_path = '../../' . $relative_path;
    @unlink($relative_path . '/_magi_page_cache.js');
    html2js($relative_path,'_magi_page_cache.js');
    echo '文件生成路径为：' . $relative_path . '文件大小为:' .  filesize($relative_path. '/' . '_magi_page_cache.js' )/1024;
}



